package org.magicat.bridge.serializer;

import java.io.IOException;
import java.io.OutputStream;

public class BridgeOutput {
	
	private static int BUF_SIZE = 4096;
	
	private OutputStream os;
	private byte[] buffer = new byte[BUF_SIZE];
	private int offset = 0;
	
	public BridgeOutput(OutputStream is) {
		this.os = is;
	}
	
	public void writeBoolean(boolean b) throws IOException {
		if (offset + 2 >= BUF_SIZE) {
			flushBuffer();
		}
		buffer[offset++] = BridgeConsts.TYPE_BOOLEAN;
		if (b) {
			buffer[offset++] = 'T';
		} else {
			buffer[offset++] = 'F';
		}
	}
	
	protected void flushBuffer() throws IOException {
		os.write(buffer, 0, offset);
		offset = 0;
	}

	public void writeInt(int i) throws IOException {
		if (offset + 5 >= BUF_SIZE) {
			flushBuffer();
		}
		buffer[offset++] = BridgeConsts.TYPE_INT;
		buffer[offset++] = (byte) (i >> 24);
		buffer[offset++] = (byte) ((i >> 16) & 0xFF);
		buffer[offset++] = (byte) ((i >> 8) & 0xFF);
		buffer[offset++] = (byte) (i & 0xFF);
	}
	
	public void writeLong(long l) throws IOException {
		if (offset + 9 >= BUF_SIZE) {
			this.flushBuffer();
		}
		buffer[offset++] = BridgeConsts.TYPE_LONG;
		buffer[offset++] = (byte) ((l >> 56) & 0xFF);
		buffer[offset++] = (byte) ((l >> 48) & 0xFF);
		buffer[offset++] = (byte) ((l >> 40) & 0xFF);
		buffer[offset++] = (byte) ((l >> 32) & 0xFF);
		buffer[offset++] = (byte) ((l >> 24) & 0xFF);
		buffer[offset++] = (byte) ((l >> 16) & 0xFF);
		buffer[offset++] = (byte) ((l >> 8) & 0xFF);
		buffer[offset++] = (byte) ((l) & 0xFF);
	}
	
	public void writeShort(short s) throws IOException {
		if (offset + 3 >= BUF_SIZE) {
			this.flushBuffer();
		}
		buffer[offset++] = BridgeConsts.TYPE_SHORT;
		buffer[offset++] = (byte) ((s >> 8) & 0xFF);
		buffer[offset++] = (byte) ((s) & 0xFF);
	}
	
	public void writeString(String s) throws IOException {
		
		if (offset + 1 >= BUF_SIZE) {
			this.flushBuffer();
		}
		this.buffer[offset++] = BridgeConsts.TYPE_STRING;
		
		int length = s.length() * 2;
		int dis = BUF_SIZE - offset;
		
		int start = 0;
		while (start < length) {
			if (length - start > dis) {
				writeString(s, start, dis);
				start += dis;
				this.flushBuffer();
			} else {
				writeString(s, start, length - start);
				start += length - start;
			}
		}
	}
	
	private void writeString(String s, int start, int dis) {
		for (int i = start; i < start + dis; i ++) {
			char c = s.charAt(i);
			
		}
	}

	public void writeByte(byte b) {
		
	}
	
	public void writeDouble(double d) {
		
	}
	
	public void writeFloat(float f) {
		
	}
	
	public void writeChar(char c) {
		
	}
	
	public void writeObject(Object o) {
		
	}
}
